package com.media.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    /**
     * post 请求  会执行 dopost方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object doGet;
        doGet(request,response);
         //System.out.println("用户 post 请求");
    }

    /**
     *get 请求 会执行doget方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //out.print();
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();

        if ("1".equals(request.getParameter("invalidate")) && session.getAttribute("username") !=null){
            session.invalidate();
        //session.removeAttribute("username");
        response.sendRedirect("login.jsp");}
        try{
            //建立数据库连接
            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/books";
            Connection connection = DriverManager.getConnection(url,"root","root");

            //sql模板
            String sql = "select * from user where username = ? and password = ?";
            //使用PreparedStatement对象执行sql语句
            PreparedStatement ps = connection.prepareStatement(sql);

            ps.setString(1,username);
            ps.setString(2,password);

            ResultSet rs = ps.executeQuery();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();

            if (rs.next()){
                //表示登录成功
                session.setAttribute("username","username");
                response.sendRedirect("home.jsp");
            }else{
                //表示登录未成功
                out.print("登录失败，3秒之后跳转登陆页面");
                response.setHeader("refresh","3;url=login.jsp");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
